package com.company.util;


import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @date : 2022/3/25 22:02
 * 事务管理类
 */

@Component("transactionManager")
//@Aspect
public class TransactionManager {
    private ConnectionUtils connectionUtils;

    @Pointcut("execution(public * com.company.aop.service.impl.AccountServiceImpl.*(..))")
    private void pointCutExp() {
    }

    @Autowired
    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    /**
     * 开启事务
     */
    @Before("pointCutExp()") // 前置通知
    public void beginTransaction() {
        try {
            System.out.println("开启事务...");
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    @AfterReturning("pointCutExp()") // 后置事务
    public void commit() {
        try {
            System.out.println("提交事务...");
            connectionUtils.getThreadConnection().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    @AfterThrowing("pointCutExp()") // 异常使用
    public void rollback() {
        try {
            System.out.println("回滚事务...");
            connectionUtils.getThreadConnection().rollback();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 释放连接
     */
    @After("pointCutExp()") // 最终事务
    public void release() {
        try {
            System.out.println("释放连接...");
            connectionUtils.getThreadConnection().close();//还回连接池中
            connectionUtils.removeConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
